package com.lazydong.apiforward.client.gui.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.StrUtil;
import com.lazydong.apiforward.client.global.GlobalData;
import com.lazydong.apiforward.client.gui.constant.CommonConstant;
import com.lazydong.apiforward.client.gui.enums.PathEnum;
import com.lazydong.apiforward.client.gui.pages.appmain.AppMainPageConfig;
import com.lazydong.apiforward.client.gui.pages.appmain.Environment;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 服务器域名相关
 */
public class DomainUtil {

    static class LocalDomain {
        String domain;
        String ip;
    }

    public static String serverDomain;
    public static String serverIp;

    static {
        if (!FileUtil.exist(CommonConstant.serverIpPortFile)) {
            writeServerIpPortFile(CommonConstant.serverIpPortFile);
        }
        serverDomain = FileUtil.readString(CommonConstant.serverIpPortFile, StandardCharsets.UTF_8);
        String[] split0 = serverDomain.split("://");
        String[] split1 = split0[1].split(":");
        serverIp = split1[0];
    }

    public static void writeServerIpPortFile(String serverIpPortFile) {
        FileUtil.writeString(CommonConstant.serverIpPortDef, serverIpPortFile, StandardCharsets.UTF_8);
    }

    public static void updateLocalHosts() {
        List<LocalDomain> localHosts = getLocalHosts();
        List<String> oldHostsLines = FileUtil.readLines(PathEnum.HOSTS.path, StandardCharsets.UTF_8);
        List<String> newHostsLines = new ArrayList<>(oldHostsLines);
        Iterator<String> iterator = newHostsLines.iterator();
        boolean delFlag = false;
        while (iterator.hasNext()) {
            String str = iterator.next();
            if (str.contains(CommonConstant.hostsStartSign)) {
                delFlag = true;
            }
            if (delFlag) {
                iterator.remove();
            }
            if (str.contains(CommonConstant.hostsEndSign)) {
                delFlag = false;
            }
        }
        newHostsLines.add(CommonConstant.hostsStartSign);
        for (LocalDomain localHost : localHosts) {
            newHostsLines.add(localHost.ip + " " + localHost.domain);
        }
        newHostsLines.add(CommonConstant.hostsEndSign);
        // 对比两者数据是否一致
        if (isDiff(oldHostsLines, newHostsLines)) {
            writeHosts(newHostsLines);
        }
    }

    private static List<LocalDomain> getLocalHosts() {
        AppMainPageConfig appMainPageConfig = GlobalData.APP_MAIN_CONFIG.get();
        List<LocalDomain> localHosts = new ArrayList<>();
        LocalDomain localDomain = new LocalDomain();
        localDomain.domain = appMainPageConfig.forwardLocalDomain;
        localDomain.ip = appMainPageConfig.forwardLocalIp;
        localHosts.add(localDomain);

        LocalDomain serverDomain = new LocalDomain();
        serverDomain.domain = appMainPageConfig.forwardServerDomain;
        serverDomain.ip = serverIp;
        localHosts.add(serverDomain);

        if (GlobalData.BLOCKER_STATUS.get()) {
            Environment environment = GlobalData.GLOBAL_ENVIRONMENT.get();
            if (environment != null && environment.envIp != null) {
                LocalDomain proxyDomain = new LocalDomain();
                proxyDomain.domain = appMainPageConfig.proxyTargetDomain;
                proxyDomain.ip = environment.envIp;
                localHosts.add(proxyDomain);
            }
        }
        return localHosts;
    }

    private static void writeHosts(List<String> hostsLines) {
        try {
            FileUtil.writeLines(hostsLines, PathEnum.HOSTS.path, StandardCharsets.UTF_8);
        } catch (IORuntimeException exception) {
            DialogMsgUtil.guideModifyHostsPerm();
        }
    }

    private static boolean isDiff(List<String> oldHostsLines, List<String> newHostsLines) {
        if (oldHostsLines.size() != newHostsLines.size()) {
            return true;
        }
        for (int i = 0; i < oldHostsLines.size(); i++) {
            String str1 = oldHostsLines.get(i);
            String str2 = newHostsLines.get(i);
            if (!StrUtil.equals(str1, str2)) {
                return true;
            }
        }
        return false;
    }
}
